package com.example.mq.common.tool;

import java.io.*;

// BinaryTool 用于将对象序列化为字节数组或从字节数组反序列化对象
public class BinaryTool {

    // 将对象序列化为字节数组
    public static byte[] toBytes(Object object) throws IOException {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            // 将对象写入 ObjectOutputStream
            objectOutputStream.writeObject(object);
            // 获取字节数组
            return byteArrayOutputStream.toByteArray();
        }
    }

    // 从字节数组反序列化为对象
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
             ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            // 从字节数组读取对象
            return objectInputStream.readObject();
        }
    }
}
